/**
 * Date:2019年4月4日 下午2:42:09
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved
 */

package com.xue.service.sys;
/**
 * Description: TODO <br/> 
 * Date:2019年4月4日 下午2:42:09 <br/> 
 * @author xuejianxin
 */

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CodeTranslatorImpl implements ICodeTranslator {

	@Autowired
	private List<ICode> codeMapServiceList;
	private Map<String, ICode> codeMapServiceMap;

	@SuppressWarnings("unchecked")
	@Override
	public <T> T translate(String codeType, String code) {
		initCodeMapServiceMap();
		// 判断是否syscode,如果是
		String[] codeTempArray = codeType.split("_");
		String options = "";
		if ("0".equals(codeTempArray[0]) && codeTempArray.length > 1) {
			codeType = "0";
			options = codeTempArray[1];
		}
		ICode codeService = codeMapServiceMap.get(codeType);
		return (T) codeService.codeMap(options).get(code);
	}

	private void initCodeMapServiceMap() {
		if (null == codeMapServiceMap) {// 缓存代码服务类
			codeMapServiceMap = codeMapServiceList.stream()
					.collect(Collectors.toMap(ICode::codeType, Function.identity(), (k1, k2) -> {
						throw new RuntimeException(String.format("Duplicate key for values %s and %s", k1, k2));
					}));

		}
	}

}
